<template>
  <div class="page-search">
    <s-form v-bind="searchFormConfig" v-model="formData" ref="searchformRef">
      <template #header>
        <h2>高级检索</h2>
      </template>
      <template #footer>
        <div class="footer-btns">
          <el-button icon="el-icon-refresh-right" @click="resetClick"
            >重置</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearchClick"
            >搜索</el-button
          >
        </div>
      </template>
    </s-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType } from 'vue'
import SForm from '@/base-ui/form'

import { IForm } from '@/base-ui/form'

export default defineComponent({
  components: {
    SForm
  },
  props: {
    searchFormConfig: {
      type: Object as PropType<IForm>,
      require: true
    }
  },
  emits: ['resetBtnClick', 'searchBtnClick'],
  setup(props, { emit }) {
    // 双向绑定中的key应该是用配置文件searchFormConfig中的field属性决定的
    // 1.formData中的属性动态决定
    const formItems = props.searchFormConfig?.formItems ?? []
    const formItemData: any = {}
    for (const item of formItems) {
      formItemData[item.field] = ''
    }

    const formData = ref(formItemData)
    // const formData = ref({
    //   id: '',
    //   name: '',
    //   password: '',
    //   sport: '',
    //   createTime: ''
    // })

    // 2.重置按钮
    const resetClick = () => {
      // 写法一：对formData里的每一个属性逐一修改
      for (const key in formItemData) {
        formData.value[key] = formItemData[key]
      }

      // 将重置、搜索两个按钮的事件传给父组件user，父组件再调用PageContent里的方法进行网络请求
      emit('resetBtnClick')

      // 直接改变一整个formData对象行不通, 对象的引用指向了formItemData
      // 写法二:
      // formData.value = formItemData
    }

    // 3.搜索按钮
    const handleSearchClick = () => {
      emit('searchBtnClick', formData.value)
    }

    return {
      formData,
      resetClick,
      handleSearchClick
    }
  }
})
</script>

<style scoped>
.footer-btns {
  text-align: right;
  padding: 0px 30px 20px 0;
}
</style>
